"""
对话服务
处理与 OpenAI Chat API 的交互
"""
from typing import Iterator, Dict, Any
from openai import OpenAI
from app.core.config import settings


class ChatService:
    """对话服务类"""
    
    def __init__(self):
        self.client = OpenAI(
            api_key=settings.OPENAI_API_KEY,
            base_url=settings.OPENAI_BASE_URL
        )
        self.model = settings.CHAT_MODEL
    
    def generate_answer_stream(self, question: str, context: str) -> Iterator[str]:
        """
        基于上下文生成答案（流式）
        
        Args:
            question: 用户问题
            context: 检索到的上下文
            
        Yields:
            答案片段
        """
        messages = [
            {
                "role": "system",
                "content": "你是一个helpful的助手，严格根据提供的文本内容回答用户问题。"
            },
            {
                "role": "user",
                "content": f"基于以下内容回答问题：\n\n{context}\n\n问题：{question}"
            }
        ]
        
        stream = self.client.chat.completions.create(
            model=self.model,
            messages=messages,
            stream=True
        )
        
        for chunk in stream:
            if chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content


# 全局服务实例
chat_service = ChatService()

